import Vue from "vue";
import VueRouter from "vue-router";
import Login from "../components/Login.vue";
import Home from "../components/Home.vue";
import Welcome from "../components/Welcome.vue";
import User from "../components/user/User.vue";
import Rights from "../components/power/Rights.vue";
import Roles from "../components/power/Roles.vue";

Vue.use(VueRouter);

const routes = [
  // 如果访问根目录，自动从定向到登录路由
  {
    path: "/",
    redirect: "/login",
  },
  // 通过 /login路径访问时，调用Login
  {
    path: "/login",
    component: Login,
  },
  {
    path: "/home",
    component: Home,
    // 定义子路由，当访问home 自动会访问welcome
    redirect: "/welcome",
    children: [
      { path: "/welcome", component: Welcome },
      { path: "/users", component: User },
      { path: "/rights", component: Rights },
      { path: "/roles", component: Roles },
    ],
  },
];
const router = new VueRouter({
  routes,
});
// 挂载路由导航守卫，用于控制访问权限
router.beforeEach((to, form, next) => {
  // to 将要访问的路径
  // from  代表从哪个路劲跳转而来``
  // next 是一个函数，表示放行
  // 如果访问的是login 直接放行
  if (to.path === "/login") return next();
  // 获取token
  const tonkerStr = window.sessionStorage.getItem("token");
  // 如果没有token跳转login next（）放行 next('/login') 强制跳转
  if (!tonkerStr) return next("/login");
  // 有token 放行
  else next();
});

export default router;